Observations
We have noticed a number of parsing differences between the Masterminds/html5-php parser and the HTML5 specification. We think that the root cause of those issues drills down to the use of PHP’s default parser, loadHTML, DOMImplementation, etc. The lack of HTML5 support by PHP is known and we contacted them asking to make it more clear in the documentation in order to raise awareness for these security issues.
This behavior becomes security-relevant when HTML sanitizers use the Masterminds/html5-php parser. We have come across multiple PHP sanitizers that are vulnerable to bypasses due to using Masterminds/html5-php.
Exploitation
Here are examples of the differentials, and how attackers can leverage these in order to bypass sanitizers.
Comments:
According to the XML specification (XHTML), comments must end with the characters -->
.
On the other hand, the HTML specification states that a comment’s text ‘must not start with the string >
, nor start with the string ->
‘.
When parsing the following string in a browser, the comment will end before the p
tag. But when parsing with Masterminds/html5-php
the p
tag will be considered a comment:
- Input:
<!---><p>
- Browser (HTML5 specification) output:
<!----><p></p>
- Masterminds/html5-php parser output:
<!---><p>-->
An attacker can input the following payload <!---><xss>-->
. While the parser considers the xss
tag as a comment, the browser will end the comment right before and render the xss
tag as expected.
Processing instructions (PI) elements (known, but we encounter sanitizer bypasses due to this)
Processing instructions elements exist in XML specification but in HTML5 the characters <?
opens a comment and ends it at the first occurrence of greater than >
.
Attackers can create the following Processing Instruction <?xml >s<img src=x onerror=alert(1)> ?>
and while no img
tag is rendered in Masterminds/html5-php the browser will create a comment and end it at the first >
character, rendering the img
tag.
Foreign content elements
HTML5 introduced two foreign elements (math and svg) which follow different parsing specifications than HTML. Masterminds/html5-php doesn’t take it into account, causing other parsing differentials and sanitizers bypass such as:
<svg><p><style><!--</style><xss>--></style>
noscript
element
Depending if scripting is enabled (enabled by default in browsers) the noscript
element parses its content differently:
- If scripting is enabled, then the content is rendered as raw data
- If scripting is disabled, then the content is rendered as HTML
Masterminds/html5-php parses according to disabled scripting, which is different than the default browsers’ parsing.
This is not wrong per se, but still can cause some mXSS such as:<noscript><p alt="</noscript><img src=x onerror=alert(1)>">